<template>
  <current>
    <div class="common-container flex flex-col h-full">
      <head-title title="访视">
        <template #right>
          <el-button v-if="!addDisabled" type="primary" @click="add">新受试者</el-button>
          <el-tooltip v-else content="项目未发布，请联系项目经理">
            <el-button disabled type="primary">新受试者</el-button>
          </el-tooltip>
        </template>
      </head-title>

      <div class="content-wrap center-box flex flex-1 flex-col h0 w-full">
        <div class="header-wrap">
          <div class="common-search ym-box">
            <SearchForm :form="searchForm" :center-options="state.centerOptions" @search="search" />
            <div>
              <refresh-btn @refresh="search" />
            </div>
          </div>
        </div>

        <div ref="tableRef" class="table-wrap ym-box">
          <div v-loading="tableLoading" class="card-box h-full">
            <div v-if="tableData.length > 0" class="card-list">
              <el-row :gutter="20" :style="{ width: responseWidth }">
                <el-col v-for="v in tableData" :key="v.subId" class="card-item">
                  <base-info
                    :info="v"
                    :class="{ 'is-active': currentData.subId === v.subId }"
                    @click="handleClick(v)"
                  />
                </el-col>
              </el-row>
            </div>

            <div v-else class="h-full empty-block" :style="{ width: responseWidth }">暂无数据</div>
          </div>

          <pagination
            v-model:currentPage="pageObj.pageNum"
            :page-size="pageObj.pageSize"
            :total="pageObj.total"
            @pagination="search"
          />
        </div>
      </div>
    </div>

    <add-dialog
      v-model:visible="dialogVisible"
      :center-options="state.centerOptions"
      @search="search"
    />
  </current>
</template>

<script lang="ts" setup>
import { nextTick, onBeforeUnmount, onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import BaseInfo from './components/BaseInfo.vue'
import RefreshBtn from '@/components/CommonSearch/RefreshBtn/index.vue'
import HeadTitle from '@/components/HeaderTitle/index.vue'
import { Pagination } from '@/components/Pagination/index'
import Current from '../current/index.vue'
import AddDialog from './addDialog.vue'
import SearchForm from './searchForm.vue'

import ProjectApi from '@/api/project/info'
import StationApi from '@/api/project/station'
import SubjectApi from '@/api/project/subject'

import { debounce } from '@/utils/debounce'

import { UNPUBLISH } from '@/configs/codeMaps'
import { commonHandle } from '@/views/mixins/common'
import IBaseObj from '#/index'

const router = useRouter()

const route = useRoute()
const getRouteQuery = () => {
  const { pid, pname }: any = route.query
  routeState.pid = pid
  routeState.pname = pname
}

const { state: tableState, handleSearch } = commonHandle()
const { pageObj, tableData, tableLoading }: IBaseObj = toRefs(tableState)

const searchForm = reactive({
  stationId: '',
  sic: '',
  pid: '',
})

const routeState = reactive({
  pid: '',
  pname: '',
})

const dialogVisible = ref(false)

const responseWidth = ref('')
const tableRef = ref()

const calcWidth = () => {
  nextTick(() => {
    const tableWidth = tableRef.value.offsetWidth
    // padding 40px
    const tableContentWidth = tableWidth - 40
    // item width 300px
    responseWidth.value = Math.floor(tableContentWidth / 300) * 300 + 'px'
  })
}

const getCenterOptions = async () => {
  const ret = await StationApi.queryStationList(routeState.pid)
  state.centerOptions = ret || []
}

const search = () => {
  handleSearch(SubjectApi.querySubject, { ...searchForm, pid: routeState.pid })
}

const add = () => {
  dialogVisible.value = true
}

const state: IBaseObj = reactive({
  currentData: {},
  centerOptions: [],
})

const { currentData } = toRefs(state)
const handleClick = (v: IBaseObj) => {
  router.push(
    `/project/subject/detail?pid=${routeState.pid}&pname=${routeState.pname}&subId=${v.subId}`
  )
  state.currentData = v
}

const _resizeHandle = debounce(calcWidth, 50)

onMounted(() => {
  calcWidth()
  window.addEventListener('resize', _resizeHandle)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', _resizeHandle)
})

const addDisabled = ref(false)
const getProjectDetail = async () => {
  const ret = await ProjectApi.getProjectInfo(routeState.pid)
  if (ret) {
    addDisabled.value = ret?.enable !== UNPUBLISH
  }
}

const init = () => {
  getRouteQuery()
  getCenterOptions()
  search()
  getProjectDetail()
}
init()

// onActivated(() => {
//   window.addEventListener('resize', _resizeHandle)
// })

// onDeactivated(() => {
//   window.removeEventListener('resize', _resizeHandle)
// })
</script>

<style lang="scss" scoped>
.common-container {
  .common-search {
    display: flex;
    justify-content: space-between;
  }
}

.card {
  &-box {
    overflow: auto;
    @include scroll-bar;
  }

  &-list {
    display: flex;
    justify-content: center;
  }

  &-item {
    flex-basis: auto;
    width: 300px;
    height: 200px;
    margin-bottom: 20px;
  }
}

.empty-block {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
